import {useCallback, useState} from 'react';
import {CheckboxChangeEvent} from "antd/lib/checkbox/Checkbox";

export interface EditModalFooterUseProps {
  /** 是否新建 */
  created: boolean,
  /** 重置表单 */
  reset?: () => void,
  /** 隐藏对话框 */
  hide?: () => void,
  /** 提交成功回调 */
  onSubmitSucess?: () => void,
}

export interface EditModalFooterResult {
  /** 是否显示连续保存复选框 */
  continueSaveVisible: boolean;
  /** 是否选中连续保存复选框 */
  continueSaveChecked: boolean;
  /** 连续保存复选框Change事件 */
  onContinueSaveChange: (e: CheckboxChangeEvent) => void;
  /** 是否显示重置表单复选框 */
  resetFormVisible: boolean;
  /** 是否选中重置表单复选框 */
  resetFormChecked: boolean;
  /** 重置表单复选框Change事件 */
  onResetFormChange: (e: CheckboxChangeEvent) => void;
  /** 数据保存事件回调 */
  finishCallback: () => void;
}

/** 编辑对话框尾部控件 hook */
function useEditModalFooter(props: EditModalFooterUseProps): EditModalFooterResult {
  const {created,reset,hide,onSubmitSucess,} = props;
  const [continueSaveVisible] = useState<boolean>();
  const [continueSaveChecked, setContinueSaveChecked] = useState<boolean>(false);

  const [resetFormVisible, setResetFormVisible] = useState<boolean>(false);
  const [resetFormChecked, setResetFormChecked] = useState<boolean>(false);

  const onContinueSaveChange = useCallback((e: CheckboxChangeEvent) => {
    const checked = e.target.checked;
    if (checked) {
      setResetFormVisible(true);
    } else {
      setResetFormVisible(false);
      setResetFormChecked(false);
    }
    setContinueSaveChecked(checked);
  }, []);

  const onResetFormChange = useCallback((e: CheckboxChangeEvent) => {
    const checked = e.target.checked;
    setResetFormChecked(checked);
  }, []);

  const finishCallback = useCallback(() => {
    if (created && continueSaveChecked) {//如果是连续新增,不隐藏,重新绑定表单或者不清空
      resetFormChecked && reset && reset();
    } else {//编辑或者不是连续新增则隐藏并刷新表格
      hide && hide();
      onSubmitSucess && onSubmitSucess();
    }
  }, [created, continueSaveChecked, resetFormChecked,]);

  return {
    continueSaveVisible: continueSaveVisible || created,
    continueSaveChecked,
    onContinueSaveChange,
    resetFormVisible,
    resetFormChecked,
    onResetFormChange,
    finishCallback
  };
}

export default useEditModalFooter;
